﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.Engine
{
    [Category("Physics"), Component]
    public class AnchorPoint : EntityComponent
    { }

    [Category("Physics"), Node]
    public class Sensor : Data.ScriptNode
    {
        public virtual bool Test() { throw new NotImplementedException(); }
        public void SensorFire() 
        { 
            if (Test()) OutputTerminals[0].Fire(new Data.ScriptPayload { Physics = null, SenderRef = null });
            else OutputTerminals[1].Fire(new Data.ScriptPayload { Physics = null, SenderRef = null });
        }

        public Sensor()
        {
            AddOutput("On", null);
            AddOutput("Off", null);
        }

        public override void Initialize(Microsoft.Xna.Framework.Content.ContentManager Content)
        {
            Sim.GetModule<PhysicsModule>().AddSensor(this);
            base.Initialize(Content);
        }
    }

    [Category("Physics"), Node]
    public class DistanceSensor : Sensor
    {
        public float lowerTriggerTreshold { get; set; }

        public DistanceSensor()
        {
            AddReference("Anchor A", typeof(AnchorPoint));
            AddReference("Anchor B", typeof(AnchorPoint));
        }

        public override bool Test()
        {
            if (ReferenceTerminals[0].Target == null || ReferenceTerminals[1].Target == null) return false;
            var AP0 = ReferenceTerminals[0].Target as AnchorPoint;
            var AP1 = ReferenceTerminals[1].Target as AnchorPoint;
            if (AP0 == null || AP1 == null) return false;
            var V0 = AP0.GetWorldPosition();
            var V1 = AP1.GetWorldPosition();
            if ((V1 - V0).Length() < lowerTriggerTreshold) return true;
            return false;
        }
        
    }
}
